#ifndef ADC_H 
#define ADC_H

#include <p89lpc9351.h>

void InitADC(void)
{
    // Set adc1 channel pins as input only 
    P0M1 |= (P0M1_4 | P0M1_3 | P0M1_2 | P0M1_1);
    P0M2 &= ~(P0M1_4 | P0M1_3 | P0M1_2 | P0M1_1);

    BURST1=1; //Autoscan continuos conversion mode
    ADMODB = CLK0; //ADC1 clock is 7.3728MHz/2
    ADINS  = (ADI13|ADI12|ADI11|ADI10); // Select the four channels for conversion
    ADCON1 = (ENADC1|ADCS10); //Enable the converter and start immediately
    while((ADCI1&ADCON1)==0); //Wait for first conversion to complete
}

// ports 1-4 correspond to 0.1, 0.2, 0.3, 0.4 pins
// 0-255 corresponds to 0 to 3.3V. Assume the conversion is linear, 1 unit equals to 0.0129 V.
int getAnalog(int port)
{
    switch (port)
    {
        case 1: return AD1DAT0;
        case 2: return AD1DAT1;
        case 3: return AD1DAT2;
        case 4: return AD1DAT3;
        default : return 0;
    }
}

#endif